<template>
  <BaseDialog v-model="dialogVisible" :title="$t('travelAgency.quickCreateTeam')" width="1100px"
    :before-close="handleClose">
    <div style="display: flex; justify-content: space-between; align-items: flex-start;">
      <div class="dialog-container">
        <el-form ref="refDialogForm" v-loading="formLoading" class="set-dialog-form"
          :label-width="language === 'en' ? '180px' : '80px'" :model="formData" :rules="rules">
          <el-row>
            <!-- <el-col v-if="type == 'add'" :span="24">
          <el-form-item :label="$t('fleet.customerName')" prop="customerId">
            <SelectCustomer
              v-model="formData.customerId"
              type="add"
              :label="$t('fleet.customerName')"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="type == 'edit'" :span="24">
          <el-form-item :label="$t('fleet.customerName')">
            <TextInput
              v-model="formData.customerName"
              :placeholder="$t('fleet.customerName')"
              disabled
            />
          </el-form-item>
        </el-col> -->
            <el-col :span="24">
              <el-form-item :label="$t('travelAgency.groupPeriodName')" prop="name">
                <TextInput v-model="formData.name" clearable :placeholder="$t('travelAgency.groupPeriodName')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('travelAgency.departureDate')" prop="startTime">
                <DateTime v-model="formData.startTime" style="width: 100%" :default-time="new Date(2025, 1, 1, 0, 0, 0)"
                  :label="$t('travelAgency.departureDate')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('travelAgency.groupPeriodType')" prop="type">
                <el-radio-group v-model="formData.type">
                  <el-radio v-for="item in g_options.groupPeriodTypeOptions" :key="item.value" :value="item.value">{{
                    item.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('travelAgency.departureDays')" prop="days">
                <TextInput v-model="formData.days" verify-type="nzint" :label="$t('travelAgency.departureDays')"
                  :maxlength="4" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('travelAgency.plannedNumber')" prop="peopleCountPlan">
                <TextInput v-model="formData.peopleCountPlan" verify-type="nzint"
                  :label="$t('travelAgency.plannedNumber')" :maxlength="4" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('travelAgency.currentNumber')" prop="peopleCountReal">
                <TextInput v-model="formData.peopleCountReal" verify-type="nzint"
                  :label="$t('travelAgency.currentNumber')" :maxlength="4" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('travelAgency.groupCreator')" prop="createUser">
                <TextInput v-model="formData.createUser" :label="$t('travelAgency.groupCreator')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('travelAgency.routeType')" prop="routeType">
                <el-radio-group v-model="formData.routeType" @change="handleRouteType" disabled>
                  <el-radio v-for="item in g_options.routeTypeOptions" :key="item.value" :value="item.value">{{
                    item.label
                    }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col v-if="formData.routeType === '1'" :span="12">
              <el-form-item :label="$t('travelAgency.routeName')" prop="routeName">
                <TextInput v-model="formData.routeName" clearable :placeholder="
                g_rules.zhAndEnShowMsg(
                  g_t('public.pleaseInput'),
                  $t('travelAgency.customRouteName')
                )
              " />
              </el-form-item>
            </el-col>
            <el-col v-if="formData.routeType === '2'" :span="12">
              <el-form-item :label="$t('travelAgency.routeName')" prop="routeId">
                <el-select v-model="formData.routeId" disabled :placeholder="
                g_rules.zhAndEnShowMsg(
                  g_t('public.pleaseSelect'),
                  $t('travelAgency.routeName')
                )
              " @change="handleRouteChange">
                  <el-option v-for="item in routeList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col v-if="type === 'edit'" :span="12">
          <el-form-item :label="$t('public.status')" prop="status">
            <el-select
              v-model="formData.status"
              :placeholder="
                g_rules.zhAndEnShowMsg(
                  g_t('public.pleaseSelect'),
                  $t('public.status')
                )
              "
            >
              <el-option
                v-for="item in g_options.tourDateStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
            <el-col :span="24">
              <el-form-item :label="$t('travelAgency.groupPeriodDesc')" prop="note">
                <TextInput v-model="formData.note" type="textarea" clearable :rows="2"
                  :label="$t('travelAgency.groupPeriodDesc')" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-form ref="desDialogForm" v-loading="desFormLoading" :label-width="language === 'en' ? '180px' : '80px'"
          :model="tripFormData" :rules="desRules" style="margin-top: 10px;" class="des_form">
          <div class="tabs-container">
            <el-tabs v-model="tabValue" style="flex: 1" @tab-change="handleTabChange">
              <el-tab-pane v-for="item in g_options.lineTypeOptions" :key="item.value" :name="item.value"
                :label="item.label" class="tab_item">
                <el-form-item :label="$t('travelAgency.description')" prop="fileContent"
                  v-if="item.value!=='8' && item.value!=='3'">
                  <TextInput v-model="tripFormData.fileContent[item.value].remark" type="textarea" clearable :rows="5"
                    :label="$t('travelAgency.description')" />
                </el-form-item>
                <div v-if="item.value==='3'">
                  <el-button type="primary" style="margin-bottom: 10px" @click="handleAddTravel">{{
                    $t('travelAgency.addRoute') }}</el-button>
                  <BaseTable ref="refRouteTable" :data="formData.tripList" row-key="id" max-height="300">
                    <TableColumn :label="$t('fleet.departure')" class="ignore">
                      <TableColumn prop="startRegionCode" :label="$t('public.region')"
                        :column-width="routeColumnWidth.startRegionCode">
                        <template #default="{ row }">
                          <span>{{ g_utils.getRegionName(row.startRegionCode) }}</span>
                        </template>
                      </TableColumn>
                      <TableColumn prop="startAddress" :label="$t('public.detailAddress')"
                        :column-width="routeColumnWidth.startAddress" />
                    </TableColumn>
                    <TableColumn :label="$t('fleet.destination')" class="ignore">
                      <TableColumn prop="endRegionCode" :label="$t('public.region')"
                        :column-width="routeColumnWidth.endRegionCode">
                        <template #default="{ row }">
                          <span>{{ g_utils.getRegionName(row.endRegionCode) }}</span>
                        </template>
                      </TableColumn>
                      <TableColumn prop="endAddress" :label="$t('public.detailAddress')"
                        :column-width="routeColumnWidth.endAddress" />
                    </TableColumn>
                    <TableColumn prop="startTime" :label="$t('fleet.departureTime')"
                      :column-width="routeColumnWidth.startTime" />
                    <TableColumn prop="endTime" :label="$t('public.endTime')"
                      :column-width="routeColumnWidth.endTime" />
                    <TableColumn prop="through" :label="$t('fleet.passingScenery')"
                      :column-width="routeColumnWidth.through" />
                    <TableColumn prop="action" fixed="right" :label="$t('public.action')"
                      :column-width="routeColumnWidth.action">
                      <template #default="{ row, $index }">
                        <el-button text @click="handleTravelEdit(row, $index)">
                          {{ $t('public.edit') }}
                        </el-button>
                        <el-button text @click="handleTravelDelete(row, $index)">{{
                          $t('public.delete')
                          }}</el-button>
                      </template>
                    </TableColumn>
                  </BaseTable>
                </div>
                <div v-if="item.value==='8'">
                  <el-button type="primary" @click="addTrip">{{ $t('travelAgency.addTripTable') }}</el-button>
                  <div style="margin-top: 10px; overflow-x: auto;">
                    <el-table :data="totalTable" max-height="300" style="width: 100%;" border v-if="totalTable.length"
                      class="total_excel" :span-method="handleSpanMethod">
                      <el-table-column prop="tripDate" :label="$t('travelAgency.date')" width="100" align="center" />
                      <el-table-column prop="tripDay" :label="$t('travelAgency.tripDay')" width="70" align="center" />
                      <el-table-column prop="trip" :label="$t('travelAgency.trip')" min-width="150" align="center"
                        show-overflow-tooltip />
                      <el-table-column prop="type" :label="$t('travelAgency.type')" width="80" align="center" />
                      <el-table-column prop="content" :label="$t('travelAgency.resource')" min-width="200"
                        align="center" show-overflow-tooltip />
                      <el-table-column :label="$t('travelAgency.action')" align="center" width="120" fixed="right">
                        <template #default="{ row }">
                          <el-button text @click="handleEditDialog(row)">
                            {{ $t('public.edit') }}
                          </el-button>
                          <el-button text @click="handleDelete(row)">
                            {{ $t('public.delete') }}
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <el-empty :description="$t('travelAgency.noData')" v-else />
                  </div>
                </div>
                <div v-if="tripFormData.fileContent[item.value] && tripFormData.fileContent[item.value].fileId">
                  <el-button text @click="handleDownload(item)">{{ $t('travelAgency.downloadFile') }}</el-button>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-form>
        <div class="form-dialog-footer" style="margin-top: 10px; text-align: right;">
          <el-button plain @click="handleClose">{{
            $t('public.cancel')
            }}</el-button>
          <el-button type="primary" @click="handleSubmitForm">{{
            $t('public.confirm')
            }}</el-button>
        </div>
      </div>
    </div>
    <AddTravel v-if="addTravelVisible" v-model="addTravelVisible" :row="travelRow" :type="travelType"
      @add="handleAddTravelCb" @update="handleUpdateTravelCb" />
    <AddOrEditTripDialog v-if="addOrEditVisible" v-model="addOrEditVisible" :id="rowId" :type="addOrEditType"
      :edit-data="editData" @add="handleTotalAdd" @update="handleTotalUpdate" />
  </BaseDialog>
</template>

<script setup>
import AddTravel from '@/views/travelAgency/tourDate/component/AddTravel.vue'
import AddOrEditTripDialog from './AddOrEditTripDialog.vue'

const props = defineProps({
  routeId: {
    type: String,
    default: ''
  }
})

const dialogVisible = defineModel({
  type: Boolean,
  default: false
})

const refDialogForm = ref(null)
const formLoading = ref(false)
const formData = ref({
  customerId: '',
  name: '',
  startTime: '',
  type: '1',
  days: '',
  peopleCountPlan: '',
  peopleCountReal: '',
  createUser: '',
  routeType: '2',
  routeName: '',
  routeId: '',
  note: '',
  tripList: [],//行结构化信息
  routeResources: [], // 食住...
  routeResourceTotals: [] // 总表
  // status: ''
})
const rules = {
  customerId: g_rules.selectRule(g_t('hotel.customer')),
  name: g_rules.commonInputText(g_t('travelAgency.groupPeriodName')),
  startTime: g_rules.selectRule(g_t('travelAgency.departureDate')),
  type: g_rules.selectRule(g_t('travelAgency.groupPeriodType')),
  days: g_rules.departureDays,
  peopleCountPlan: g_rules.peopleCountPlan,
  peopleCountReal: g_rules.peopleCountReal,
  routeType: g_rules.selectRule(g_t('travelAgency.routeType')),
  routeName: g_rules.commonInputText(g_t('travelAgency.customRouteName')),
  routeId: g_rules.selectRule(g_t('travelAgency.routeName')),
  tripList: [
    {
      required: true,
      message: g_t('travelAgency.pleaseAddRoute'),
      trigger: ['blur', 'change']
    }
  ]
  // status: g_rules.selectRule(g_t('fleet.status'))
}

// 添加验证规则
const desRules = {
  fileId: [
    {
      validator: (rule, value, callback) => {
        callback()
      },
      trigger: ['blur', 'change']
    }
  ],
  fileContent: [
    {
      validator: (rule, value, callback) => {
        const find = Object.entries(tripFormData.value.fileContent).find(
          item => item[1].remark
        )
        if (!find) {
          callback(new Error(g_t('travelAgency.pleaseInputDescription')))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ]
}
const routeList = ref([])
const refRouteTable = ref(null)
const routeColumnWidth = ref({})
const addTravelVisible = ref(false)
const travelRow = ref({})
const travelType = ref('add')
const travelTableIndex = ref(0)

// 添加响应式变量和函数
const desDialogForm = ref(null)
const desFormLoading = ref(false)
const totalTable = ref([])
const addOrEditVisible = ref(false)
const addOrEditType = ref('add')
const rowId = ref('')
const editData = ref(null)
const tabValue = ref(g_options.lineTypeOptions[0].value)

const fileContent = Object.fromEntries(
  g_options.lineTypeOptions.map(item => [
    item.value,
    { fileId: '', remark: '' }
  ])
)

const tripFormData = ref({
  fileId: '',
  fileContent: g_.cloneDeep(fileContent)
})

watch(
  () => formData.value.tripList,
  nv => {
    nextTick(() => {
      useTableColumnWidth({
        refTable: refRouteTable.value
      }).getTableColumnWidth(data => {
        routeColumnWidth.value = data
      })
    })
  },
  {
    deep: true
  }
)

onMounted(() => {
  formData.value.routeId = props.routeId
  getRouteDropList()
  getRouteDetail()
})

const getRoutefileContent = () => {
  // 创建一个Promise数组来处理所有异步请求
  const promises = []

  // 遍历所有tab类型，获取对应的文件内容
  g_options.lineTypeOptions.forEach(item => {
    // 跳过不需要获取文件内容的tab（3和8是特殊tab）
    if (item.value !== '3' && item.value !== '8') {
      const promise = g_api.travelAgency
        .apiRouteResourceQuery({
          type: item.value,
          routeId: formData.value.routeId
        })
        .then(({ code, data }) => {
          if (code === '200' && data) {
            tripFormData.value.fileContent[item.value] = {
              ...data,
            }
          }
        })

      promises.push(promise)
    }
  })

  // 等待所有请求完成
  return Promise.all(promises)
    .then(() => {
      formData.value.routeResources = handleRouteResources()
    })
    .catch(error => {
      console.error(g_t('travelAgency.errorFetchingFileContent'), error)
    })
}

const getRouteDropList = () => {
  g_api.travelAgency.apiRouteDropList({}).then(({ code, data }) => {
    if (code === '200' && data) {
      routeList.value = data
      formData.value.routeName = data.find(item => item.id === formData.value.routeId)?.name || ''
    }
  })
}

// 选择固定路线，查询detail覆盖原有下部分数据
const getRouteDetail = async () => {
  desFormLoading.value = true
  try {
    // 并行执行两个异步操作
    const [routeDetailResult] = await Promise.all([
      g_api.travelAgency.apiRouteDetail({ id: formData.value.routeId }),
      getRoutefileContent()
    ])

    const { code, data } = routeDetailResult
    if (code === '200' && data) {
      formData.value.tripList = data.routeTrips
      formData.value.routeResourceTotals = data.routeResourceTotals
      // 转换数据格式
      if (data.routeResourceTotals && data.routeResourceTotals.length > 0) {
        totalTable.value = transformTotalTable(data.routeResourceTotals)
      } else {
        totalTable.value = []
      }
    }
  } catch (error) { } finally {
    desFormLoading.value = false
  }
}

const handleClose = _ => {
  dialogVisible.value = false
}

const handleRouteType = data => {
  const fileContent = { ...tripFormData.value.fileContent }
  formData.value.routeName = ''
  formData.value.routeId = ''
  formData.value.tripList = []//行结构化信息
  formData.value.routeResourceTotals = [] //总表
  totalTable.value = []
  for (const key in fileContent) {
    fileContent[key].fileId = ''
    fileContent[key].remark = ''
    fileContent[key].type = key
  }
  tripFormData.value.fileContent = fileContent
  setTimeout(() => {
    refDialogForm.value.clearValidate(['routeName'])
  })
}

const handleRouteChange = data => {
  formData.value.routeName =
    routeList.value.find(item => item.id === data)?.name || ''
  if (formData.value.routeType === '2' && formData.value.routeId) {
    getRouteDetail()
  }
}

const handleAddTravel = _ => {
  addTravelVisible.value = true
  travelType.value = 'add'
}

const handleTravelEdit = (row, i) => {
  addTravelVisible.value = true
  travelRow.value = row
  travelType.value = 'edit'
  travelTableIndex.value = i
}

const handleTravelDelete = (row, i) => {
  g_utils.deleteConfirm().then(() => {
    formData.value.tripList.splice(i, 1)
    ElMessage.success(g_t('public.deleteSuccess'))
  }).catch(() => { })
}

const handleAddTravelCb = data => {
  formData.value.tripList.push(data)
}

const handleUpdateTravelCb = data => {
  formData.value.tripList.splice(travelTableIndex.value, 1, data)
}

// 添加表格合并方法
const handleSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 日期、天数、行程列需要合并，每7行合并为1行
  if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 5) {
    // 每7行的第一个行显示合并，其余6行隐藏
    if (rowIndex % 7 === 0) {
      return {
        rowspan: 7,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }

  // 其他列不合并
  return {
    rowspan: 1,
    colspan: 1
  }
}

// 添加相关方法
const addTrip = () => {
  addOrEditVisible.value = true
  addOrEditType.value = 'add'
}

const handleEditDialog = row => {
  // 查找具有相同rowId的所有行数据
  const relatedRows = totalTable.value.filter(item => item.rowId === row.rowId)
  // 将7行数据转换为一行数据
  const data = {
    tripDate: row.tripDate,
    tripDay: row.tripDay,
    trip: row.trip,
    rowId: row.rowId,
  }

  // 根据不同类型设置对应字段
  relatedRows.forEach(item => {
    switch (item.type) {
      case g_t('travelAgency.meal'):
        data.meal = item.content
        break
      case g_t('travelAgency.hotel'):
        data.hotel = item.content
        break
      case g_t('travelAgency.car'):
        data.car = item.content
        break
      case g_t('travelAgency.play'):
        data.play = item.content
        break
      case g_t('travelAgency.shop'):
        data.shop = item.content
        break
      case g_t('travelAgency.enjoy'):
        data.enjoy = item.content
        break
      case g_t('travelAgency.other'):
        data.other = item.content
        break
    }
  })

  // 将转换后的数据设置到响应式变量中
  editData.value = data

  // 显示编辑对话框
  addOrEditVisible.value = true
  addOrEditType.value = 'edit'
  rowId.value = data.rowId
}

const handleDelete = row => {
  g_utils
    .deleteConfirm()
    .then(() => {
      // 根据row.rowId删除对应的数据
      totalTable.value = totalTable.value.filter(item => item.rowId !== row.rowId)
      // 更新formData中的routeResourceTotals
      formData.value.routeResourceTotals = totleTableToRouteResources(totalTable.value)
      ElMessage.success(g_t('travelAgency.deleteTripSuccess'))
    })
    .catch(() => { })
}

// 添加数据转换方法
const totleTableToRouteResources = (totalTable) => {
  // 多行数据转一行数据
  const result = []
  const groupedData = {}

  // 按 rowId 分组数据
  totalTable.forEach(item => {
    if (!groupedData[item.rowId]) {
      groupedData[item.rowId] = []
    }
    groupedData[item.rowId].push(item)
  })

  // 将每组7行数据转换为一行数据
  Object.values(groupedData).forEach(group => {
    if (group.length > 0) {
      const firstItem = group[0]
      const rowData = {
        tripDate: firstItem.tripDate,
        tripDay: firstItem.tripDay,
        trip: firstItem.trip,
        rowId: firstItem.rowId
      }

      // 根据不同类型设置对应字段
      group.forEach(item => {
        switch (item.type) {
          case g_t('travelAgency.meal'):
            rowData.meal = item.content
            break
          case g_t('travelAgency.hotel'):
            rowData.hotel = item.content
            break
          case g_t('travelAgency.car'):
            rowData.car = item.content
            break
          case g_t('travelAgency.play'):
            rowData.play = item.content
            break
          case g_t('travelAgency.shop'):
            rowData.shop = item.content
            break
          case g_t('travelAgency.enjoy'):
            rowData.enjoy = item.content
            break
          case g_t('travelAgency.other'):
            rowData.other = item.content
            break
        }
      })

      result.push(rowData)
    }
  })

  return result
}

const handleDownload = item => {
  const { fileId, fileName } = tripFormData.value.fileContent[item.value]
  g_api.travelAgency
    .apiFileDownload({
      fileId
    })
    .then(res => {
      if (res.code === '200' && res.data) {
        g_utils.downloadFile(res.data, fileName)
      }
    })
    .finally(() => { })
}

// 添加数据转换方法
const transformTotalTable = (data) => {
  const convertedData = []
  data.forEach(item => {
    // 根据7个类型转换为7条数据
    const types = [
      { type: g_t('travelAgency.meal'), key: 'meal' },
      { type: g_t('travelAgency.hotel'), key: 'hotel' },
      { type: g_t('travelAgency.car'), key: 'car' },
      { type: g_t('travelAgency.play'), key: 'play' },
      { type: g_t('travelAgency.shop'), key: 'shop' },
      { type: g_t('travelAgency.enjoy'), key: 'enjoy' },
      { type: g_t('travelAgency.other'), key: 'other' }
    ]

    types.forEach(typeInfo => {
      convertedData.push({
        tripDate: item.tripDate,
        tripDay: item.tripDay,
        trip: item.trip,
        type: typeInfo.type,
        content: item[typeInfo.key] || g_t('travelAgency.none'),
        routeId: item.routeId,
        tenantId: item.tenantId,
        id: item.id,
        rowId: item.rowId
      })
    })
  })

  return convertedData
}

// 添加数据处理方法
const handleTotalAdd = (formTotalData) => {
  totalTable.value = routeResourcesTototleTable(formTotalData)
  // 更新formData中的routeResourceTotals
  formData.value.routeResourceTotals = totleTableToRouteResources(totalTable.value)
}

const handleTotalUpdate = (formTotalData) => {
  // 根据7个类型转换为7条数据
  const types = [
    { type: g_t('travelAgency.meal'), key: 'meal' },
    { type: g_t('travelAgency.hotel'), key: 'hotel' },
    { type: g_t('travelAgency.car'), key: 'car' },
    { type: g_t('travelAgency.play'), key: 'play' },
    { type: g_t('travelAgency.shop'), key: 'shop' },
    { type: g_t('travelAgency.enjoy'), key: 'enjoy' },
    { type: g_t('travelAgency.other'), key: 'other' }
  ]

  // 生成更新后的7行数据
  const updatedRows = types.map(typeInfo => ({
    tripDate: formTotalData.tripDate,
    tripDay: formTotalData.tripDay,
    trip: formTotalData.trip,
    type: typeInfo.type,
    content: formTotalData[typeInfo.key] || g_t('travelAgency.none'),
    rowId: formTotalData.rowId
  }))

  // 找到具有相同rowId的第一行数据的索引
  const firstRowIndex = totalTable.value.findIndex(item => item.rowId === formTotalData.rowId)

  if (firstRowIndex !== -1) {
    // 创建新的数组，替换原有的7行数据
    const newTotalTable = [...totalTable.value]
    // 移除原有的7行数据
    newTotalTable.splice(firstRowIndex, 7)
    // 在相同位置插入更新后的7行数据
    newTotalTable.splice(firstRowIndex, 0, ...updatedRows)
    totalTable.value = newTotalTable
    // 更新formData中的routeResourceTotals
    formData.value.routeResourceTotals = totleTableToRouteResources(totalTable.value)
  }
}

const routeResourcesTototleTable = (formTotalData) => {
  // 一行数据转多行数据
  const convertedData = []
  // 根据7个类型转换为7条数据
  const types = [
    { type: g_t('travelAgency.meal'), key: 'meal' },
    { type: g_t('travelAgency.hotel'), key: 'hotel' },
    { type: g_t('travelAgency.car'), key: 'car' },
    { type: g_t('travelAgency.play'), key: 'play' },
    { type: g_t('travelAgency.shop'), key: 'shop' },
    { type: g_t('travelAgency.enjoy'), key: 'enjoy' },
    { type: g_t('travelAgency.other'), key: 'other' }
  ]

  types.forEach(typeInfo => {
    convertedData.push({
      tripDate: formTotalData.tripDate,
      tripDay: formTotalData.tripDay,
      trip: formTotalData.trip,
      type: typeInfo.type,
      content: formTotalData[typeInfo.key] || g_t('travelAgency.none'),
      rowId: formTotalData.rowId
    })
  })

  return [...totalTable.value, ...convertedData]
}


const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    // 添加routeResources到formData
    formData.value.routeResources = handleRouteResources()
    console.log('保存的formData', formData.value)

    if (!valid) return
    formLoading.value = true
    desFormLoading.value = true

    g_api.travelAgency.apiTeamCreate(formData.value)
      .then(res => {
        if (res.code === '200') {
          ElMessage({
            message: res.message,
            type: 'success'
          })
          handleClose()
        }
      })
      .finally(() => {
        formLoading.value = false
        desFormLoading.value = false
      })
  })
}


// 添加处理routeResources的函数
const handleRouteResources = () => {
  const routeResources = []
  Object.entries(tripFormData.value.fileContent).forEach(([key, value]) => {
    // 过滤掉 key 值为 "3" 和 "8" 的项
    if (key !== '3' && key !== '8') {
      routeResources.push({
        type: key,
        fileId: value.fileId || '',
        remark: value.remark || ''
      })
    }
  })

  return routeResources
}
</script>

<style scoped lang="scss">
// 添加样式
.tabs-container {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .tab_item {
    min-height: 350px;
    max-height: 400px;
    padding-top: 10px;
    overflow-y: auto;
  }

  :deep(.el-tabs__nav.is-top) {
    width: 100%;
    justify-content: space-around;
  }
}

.total_excel th.el-table__cell {
  background-color: transparent !important;
  font-size: 14px !important;
}

.total_excel {
  &.el-table {
    border: 1px solid #000;

    td,
    th {
      border-right: 1px solid #000;
      border-bottom: 1px solid #000;
    }

    th.el-table__cell.is-leaf {
      border-bottom: 1px solid #000;
    }

    &::before {
      background-color: #000;
      height: 1px;
    }
  }
}

.dialog-container {
  width: 100%;
}

.form_footer {
  text-align: right;
}

.des_form,
.route_form {
  width: 100%;
}
</style>